package com.ktgj.service.service.impl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.ktgj.common.core.annotation.Excel;
import com.ktgj.common.core.constant.BusinessTypeConstants;
import com.ktgj.common.core.constant.CustomerConstants;
import com.ktgj.common.core.constant.VipHallConstants;
import com.ktgj.common.core.domain.R;
import com.ktgj.common.core.enums.EmHelper;
import com.ktgj.common.core.enums.TrainOrderEnum;
import com.ktgj.common.core.exception.LoginException;
import com.ktgj.common.core.keyutil.AesUtil;
import com.ktgj.common.core.utils.DateUtils;
import com.ktgj.common.core.utils.SnowFlake;
import com.ktgj.common.core.web.domain.AjaxResult;
import com.ktgj.common.redis.service.RedisService;
import com.ktgj.customer.api.RemoteCustomerService;
import com.ktgj.customer.api.domain.*;
import com.ktgj.flight.api.RemoteFlightService;
import com.ktgj.flight.api.domain.AirportApi;
import com.ktgj.flight.api.domain.AirportTerminalApi;
import com.ktgj.flight.api.domain.Terminal;
import com.ktgj.pay.api.RemotePayService;
import com.ktgj.pay.api.domain.PayTypeApi;
import com.ktgj.service.common.JTu.JingTu;
import com.ktgj.service.domain.*;
import com.ktgj.service.domain.vo.*;
import com.ktgj.service.mapper.OrderOperationlogMapper;
import com.ktgj.service.mapper.OrderitemViphallMapper;
import com.ktgj.service.mapper.ViphallMapper;
import com.ktgj.service.service.*;
import nonapi.io.github.classgraph.utils.CollectionUtils;
import org.apache.catalina.util.CustomObjectInputStream;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ktgj.service.mapper.OrderViphallMapper;
import org.springframework.transaction.annotation.Transactional;
import springfox.documentation.spring.web.json.Json;

import javax.servlet.http.HttpServletRequest;

/**
 * 贵宾厅订单Service业务层处理
 * 
 * @author ruoyi
 * @date 2021-09-03
 */
@Transactional
@Service
public class OrderViphallServiceImpl implements IOrderViphallService {
    @Autowired
    private OrderViphallMapper orderViphallMapper;

    @Autowired
    private OrderitemViphallMapper orderitemViphallMapper;

    @Autowired
    private RemoteCustomerService remoteCustomerService;

    @Autowired
    private IViphallService viphallService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private RemoteFlightService remoteFlightService;

    @Autowired
    private RemoteFlightService flightService;

    @Autowired
    private IContractLinkViphallPriceService contractLinkViphallPriceService;

    @Autowired
    private IOrderVipchannelService orderVipchannelService;

    @Autowired
    private RemotePayService payService;

    @Autowired
    private ViphallMapper viphallMapper;

    @Autowired
    private OrderOperationlogMapper orderOperationlogMapper;

    @Autowired
    private IVipchannelService vipchannelService;

    @Autowired
    private IOrderViphallService orderViphallService;

    @Autowired
    private IKtserviceOrderChannelService channelService;

    /**
     * 查询贵宾厅订单*
     *
     * @param orderviphallId 贵宾厅订单ID
     * @return 贵宾厅订单
     */
    @Override
    public OrderViphall selectOrderViphallById(Long orderviphallId) {
        return orderViphallMapper.selectOrderViphallById(orderviphallId);
    }

    /**
     * 查询贵宾厅订单列表
     *
     * @param orderViphall 贵宾厅订单* @return 贵宾厅订单
     */
    @Override
    public List<OrderViphall> selectOrderViphallList(OrderViphall orderViphall) {
        return orderViphallMapper.selectOrderViphallList(orderViphall);
    }

    /**
     * 新增贵宾厅订单*
     *
     * @param orderViphall 贵宾厅订单* @return 结果
     */
    @Override
    public int insertOrderViphall(OrderViphall orderViphall) {
        orderViphall.setCreateTime(DateUtils.getNowDate());
        return orderViphallMapper.insertOrderViphall(orderViphall);
    }

    /**
     * 修改贵宾厅订单*
     *
     * @param orderViphall 贵宾厅订单* @return 结果
     */
    @Override
    public int updateOrderViphall(OrderViphall orderViphall) {
        orderViphall.setUpdateTime(DateUtils.getNowDate());
        return orderViphallMapper.updateOrderViphall(orderViphall);
    }

    /**
     * 批量删除贵宾厅订单*
     *
     * @param orderviphallIds 需要删除的贵宾厅订单ID
     * @return 结果
     */
    @Override
    public int deleteOrderViphallByIds(Long[] orderviphallIds) {
        return orderViphallMapper.deleteOrderViphallByIds(orderviphallIds);
    }

    /**
     * 删除贵宾厅订单信息
     *
     * @param orderviphallId 贵宾厅订单ID
     * @return 结果
     */
    @Override
    public int deleteOrderViphallById(Long orderviphallId) {
        return orderViphallMapper.deleteOrderViphallById(orderviphallId);
    }

    //贵宾厅填写订单
    @Override
    public FillOrderResponse queryHallOrderInfo(String token, Long viphallId) throws Exception {
        StringBuilder builder;
        FillOrderResponse response = new FillOrderResponse();
        R<Customer> customer = remoteCustomerService.getLoginCustomerByToken(token);
        if (customer.getCode() != 200 && customer.getData() == null)
            throw new Exception(customer.getMsg());
        Viphall viphall = viphallService.selectViphallById(viphallId);
        response.setViphallName(viphall.getViphallName());
        String beginhour = viphall.getBusinessBeginhour().toString();
        if (beginhour != null) {
            builder = new StringBuilder(beginhour);
            builder.insert(builder.length() - 2, ":");
            response.setBusinessBeginhour(builder.toString());
        }
        String endhour = viphall.getBusinessEndhour().toString();
        if (endhour != null) {
            builder = new StringBuilder(endhour);
            builder.insert(builder.length() - 2, ":");
            response.setBusinessEndhour(builder.toString());
        }
        response.setSecurityCheckLocation(viphall.getSecurityCheckLocation());
        if (viphall.getAirportTerminalId() != null && !viphall.getAirportTerminalId().equals(0L)) {
            Map<String, Object> objectMap = new HashMap<>();
            objectMap.put("terminalId", viphall.getAirportTerminalId());
            R<Terminal> terminalR = remoteFlightService.flightTerminalGetInfo(objectMap);
            if (terminalR.getCode() == 200 && terminalR.getData() != null){
                response.setStartTerminal(terminalR.getData().getTerminalName());
            }
        }
        response.setCustomerName(customer.getData().getCustomerName());
        response.setContractPhoneOne(customer.getData().getContractPhoneOne());
        response.setContractPhoneTow(customer.getData().getContractPhoneTow());
        R<Long> depb = remoteCustomerService.queyUserDepositBusinessByToken(token);
        Long depositBusiness = depb.getData();
        response.setDepositBusiness(depositBusiness);
        R<Long> integralVoR = remoteCustomerService.queyUserCreditsNumByToken(token);
        Long points = integralVoR.getData();
        response.setPoints(points);
        response.setSalePrice(viphall.getSellPrice());
        CouponDto data = remoteCustomerService.queyUserCouponByToken(token, viphall.getSellPrice()).getData();
        response.setCoupon(data);
        return response;
    }

    /**
     * 贵宾厅订单生成
     *
     * @param token          请求头
     * @param viphallId      贵宾厅id
     * @param payment        应付金额
     * @param points         积分
     * @param couponId       优惠卷id
     * @param totalsalePrice 订单总金额
     * @param usedDeposit    预留款
     * @param employeeId     操作人id
     * @return
     */
    @Override
    public String saveOrder(String token, Long viphallId, String arrivalDate,
                          Long peopleNumber, BigDecimal payment, BigDecimal points, Long couponId,
                          BigDecimal totalsalePrice, BigDecimal usedDeposit, Long employeeId,
                          String contactName, String contactPhone, String usePoint, String useDeposits) throws Exception {

        CalculationVOApi calculationVOApi = new CalculationVOApi();
        List<BigDecimal> pricesList = new ArrayList<>();
        BigDecimal prices = payment;
        pricesList.add(prices);
        calculationVOApi.setPrices(pricesList);
        calculationVOApi.setAmount(Math.toIntExact(peopleNumber));
        calculationVOApi.setAdditionalAmount(1);
        calculationVOApi.setCouponId(couponId);
        calculationVOApi.setDepositAmount(usedDeposit);
        if (useDeposits.equals("false")) {
            calculationVOApi.setUseDeposit(false);
        } else if (useDeposits.equals("true")) {
            calculationVOApi.setUseDeposit(true);
        }
        calculationVOApi.setPointAmount(Integer.parseInt(points.toString()));
        if (usePoint.equals("false")) {
            calculationVOApi.setUsePoint(false);
        } else if (usePoint.equals("true")) {
            calculationVOApi.setUsePoint(true);
        }
        CalculationDTO calculationDTO = remoteCustomerService.calculationRemotely(calculationVOApi);
        if (calculationDTO.getPrice() == null) {
            throw new Exception("价格计算异常");
        }
        if (calculationDTO.getPrice().compareTo(totalsalePrice) != 0) {
            throw new Exception("支付金额发生变化");
        }


        R<Customer> customer = remoteCustomerService.getLoginCustomerByToken(token);
        Viphall viphall = viphallService.selectViphallById(viphallId);
        OrderViphall orderViphall = new OrderViphall();
        OrderitemViphall orderitemViphall = new OrderitemViphall();
        String orderSourceDesc = "购买:" + viphall.getViphallName();
        String orderType = VipHallConstants.newVip.getValue();
//        R<CustomerCard> customerCardR = remoteCustomerService.queryCardIdByCustomerId(customer.getData().getCustomerId());
        List<CustomerCard> customerCards = remoteCustomerService.queryCardIdByCustomerId(customer.getData().getCustomerId());

        for (CustomerCard customerCard : customerCards) {
            if (customerCard.getCardId() != null && customerCard.getCardId() != 0) {
                Map<String, Object> map = new HashMap<>();
                map.put("cardId", customerCard.getCardId());
                Card card = remoteCustomerService.cardInfo(map);
                if (card != null) {
                    customerCard.setCardLevel(card.getCardLevel());
                } else {
                    throw new Exception("无效的会员卡");
                }
            } else {
                throw new Exception("会员卡没有关联卡id");
            }
        }

        customerCards.sort((y, x) -> Double.compare(y.getCardLevel(), x.getCardLevel()));
        CustomerCard customerCardR = customerCards.get(0);

        //生成订单
        orderViphall.setCardNumber(customerCardR.getCardCode());
        orderViphall.setCustomerId(customer.getData().getCustomerId());
        orderViphall.setJsjId(System.currentTimeMillis());
        orderViphall.setContractViphallId(viphall.getViphallId());
        Date date = DateUtils.getNowDate();
        orderViphall.setContactName(contactName);
        orderViphall.setContactPhone(contactPhone);
        orderViphall.setStatus(CustomerConstants.waitPay.getValue());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        try {
            orderViphall.setArrivalviphallTime(format.parse(arrivalDate));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        orderViphall.setContactName(contactName);
        orderViphall.setContactPhone(contactPhone);
        orderViphall.setPeopleNumber(peopleNumber);
        orderViphall.setPaymentAmount(new BigDecimal(0.1));
        orderViphall.setPoints(points);
        orderViphall.setDepositAmount(usedDeposit);
        orderViphall.setOpemployeeId(employeeId);
        orderViphall.setTotalbasePrice(totalsalePrice);
        orderViphall.setPaymentStatus(CustomerConstants.waitPay.getValue());
        orderViphall.setCreateTime(date);
        orderViphall.setUpdateTime(date);
        if (couponId != null && couponId != 0) {
            orderViphall.setCouponNum(String.valueOf(couponId));

            R<Coupon> coupon = remoteCustomerService.couponById(couponId);

            if (coupon.getData().getCouponType().equals("CouponTypeFullMinus") || coupon.getData().getCouponType().equals("CouponTypeCashCoupon")) {
                orderViphall.setCouponAmount(coupon.getData().getCouponPrice());
            } else {
                BigDecimal price = coupon.getData().getCouponDiscount();
                BigDecimal divide = price.divide(new BigDecimal(100));
                BigDecimal countPrice = totalsalePrice.multiply(divide);
                BigDecimal couponAmount = totalsalePrice.subtract(countPrice);
                orderViphall.setCouponAmount(couponAmount);
            }
        } else {
            orderViphall.setCouponAmount(new BigDecimal(0));
        }

        SnowFlake snowFlake = new SnowFlake(0, 0);
        Long orderNum = snowFlake.nextId();
        orderViphall.setOrderNumber(orderNum.toString());
        orderViphall.setSourcewayId(1L); //1：App
        orderViphall.setDepartmentId(viphall.getDeptId());
        orderViphallMapper.addOrderViphall(orderViphall);

        //OrderViphall number = orderViphallMapper.queryByOrderNumber(orderNum);
        for (int i = 0; i < peopleNumber.intValue(); i++) {
            //生成子订单

            OrderViphall temporaryOrderViphall = orderViphallMapper.queryByOrderNumber(orderNum);

//            orderitemViphall.setOrderviphallId(orderViphall.getJsjId());
            orderitemViphall.setOrderviphallId(temporaryOrderViphall.getOrderviphallId());
            BigDecimal price = contractLinkViphallPriceService.queryPriceByviphallId(viphall.getViphallId());
            orderitemViphall.setSalePrice(price);
            orderitemViphall.setStatus(CustomerConstants.waitPay.getValue());
            orderitemViphall.setOpemployeeId(employeeId);
            orderitemViphall.setCreateTime(date);
            orderitemViphall.setPoints(points.longValue());
            orderitemViphall.setPaymentAmount(payment.divide(BigDecimal.valueOf(peopleNumber)));
            orderitemViphallMapper.insertOrderitemViphall(orderitemViphall);
        }
        List<OrderitemViphall> list = new ArrayList<>();
        list.add(orderitemViphall);
        orderViphall.setOrderitemViphalls(list);

        if ((points != null && points.longValue() > 0L) || couponId != null || (usedDeposit != null && usedDeposit.longValue() > 0L)) {
            remoteCustomerService.spend(customer.getData().getCustomerId(), points.longValue(), orderType, orderViphall.getOrderId(), orderSourceDesc, couponId, usedDeposit, employeeId);
        }
        if (customer.getData().getCustomerId() != null && customer.getData().getCustomerId() != 0l) {
            //会员消息
            String customerId = customer.getData().getCustomerId().toString();
            Map<String, String> map = new HashMap<>();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            String orderDate = sdf.format(date);
            //从哪获取订单信息
            String star = "您在" + orderDate + "预定" + viphall.getViphallName() + "请在规定时间内支付，以免影响您的行程";
            map.put("messageContent", star);
            //订单类型
            map.put("businessType", BusinessTypeConstants.viphall.getValue());
            map.put("customerId", customerId);
            map.put("businessOrderId", orderViphall.getOrderNumber().toString());
            remoteCustomerService.addCustomerMessage(map);
        }
        redisService.setCacheObject("order" + customer.getData().getCustomerId() + "o" + orderViphall.getOrderNumber(), JSON.toJSON(orderViphall), 60 * 30L, TimeUnit.SECONDS);
        return orderViphall.getOrderNumber();
    }

    /**
     * 贵宾厅订单收银台
     *
     * @param customerId
     * @return
     */
    @Override
    public Cashier queryByPayOrder(Long customerId, Long orderNumber, String businessType) throws Exception {
        Cashier cashier = new Cashier();
        Long expireTime = redisService.redisTemplate.getExpire("order" + customerId + "o" + orderNumber);
//        R<CustomerCard> customerCardR = remoteCustomerService.queryCardIdByCustomerId(customerId);
//        List<CustomerCard> customerCards = remoteCustomerService.queryCardIdByCustomerId(customerId);
//        if (customerCards == null || customerCards.size() <= 0){
//            throw new Exception("未查到会员卡信息");
//        }
//
//        OrderViphall orderViphall = null;
//        for (CustomerCard customerCard : customerCards) {
        OrderViphall orderViphall = orderViphallMapper.queryOrderViphall(customerId, orderNumber);
//            if (orderViphall != null){
//                break;
//            }
//        }
//
//        if (orderViphall == null){
//            throw new Exception("未查到数据");
//        }
        Viphall viphall = viphallService.selectViphallById(orderViphall.getContractViphallId());
        cashier.setName(viphall.getViphallName());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String format = dateFormat.format(orderViphall.getArrivalviphallTime());
        cashier.setArrivalviphallTime(format);
        cashier.setPaymentStatus(orderViphall.getPaymentStatus());
        cashier.setPayment(orderViphall.getPaymentAmount());
        if (expireTime != null && expireTime > 0) {
//            Map<String, Object> map = new HashMap<>();
//            map.put("businessType", businessType);
            List<PayTypeApi> payTypes = payService.queryPayType(businessType);
            for (PayTypeApi payType : payTypes) {
                PayTypeVo typeVo = new PayTypeVo();
                typeVo.setPayId(payType.getPayId());
                typeVo.setPayName(payType.getPayName());
                typeVo.setPayType(payType.getPayType());
                typeVo.setPayInfo(payType.getPayInfo());
                cashier.getPayType().add(typeVo);
            }
            cashier.setExpiredTime(String.valueOf(expireTime));
        } else {
            cashier.setExpiredTime("订单已超时！");
        }
        return cashier;
    }

    /**
     * 订单核销
     *
     * @param personNum
     * @param orderviphallId
     */
    @Override
    public int descOrderVipHall(int personNum, Long orderviphallId) {
        List<Long> orderItemList = orderitemViphallMapper.selectOrderitemViphallByIds(orderviphallId);
        personNum = 0;
        if (personNum <= orderItemList.size()) {
            for (int i = 0; i < personNum; i++) {
                personNum = orderitemViphallMapper.updateOrderitemViphallStatus(orderItemList.get(i), "30");
            }
        }
        return personNum;
    }

    /**
     * 支付成功页面展示
     *
     * @param orderviphallId
     * @return
     */
    @Override
    public OrderViphall selectOrderViphallNumber(Long orderviphallId) {
        return orderViphallMapper.selectOrderViphallNumber(orderviphallId);
    }

    //首页-黄金会员-进行中/已使用
    @Override
    public List<OrderConductOrUse> selectOrderViphallByStatus(Long customerId) {
        List<OrderConductOrUse> list = new ArrayList<>();
        List<ViphallDO> viphallDOS = orderViphallMapper.selectOrderViphallByStatus(customerId);
        StringBuilder builder;
        for (ViphallDO viphallDO : viphallDOS) {
            OrderConductOrUse orUse = new OrderConductOrUse();
            for (OrderViphall orderViphall : viphallDO.getOrderViphalls()) {
                orUse.setId(orderViphall.getOrderviphallId());
                orUse.setStatus(orderViphall.getStatus());
            }
            orUse.setName(viphallDO.getViphallName());
            orUse.setSecurityCheckLocation(viphallDO.getSecurityCheckLocation());
            orUse.setAddress(viphallDO.getAddress());
            String businessBeginhour = viphallDO.getBusinessBeginhour().toString();
            if (businessBeginhour != null) {
                builder = new StringBuilder(businessBeginhour);
                builder.insert(builder.length() - 2, ":");
                orUse.setBusinessBeginhour(builder.toString());
            }
            String businessEndhour = viphallDO.getBusinessEndhour().toString();
            if (businessEndhour != null) {
                builder = new StringBuilder(businessEndhour);
                builder.insert(builder.length() - 2, ":");
                orUse.setBusinessEndhour(builder.toString());
            }
            Long terminalId = viphallDO.getAirportTerminalId();
            String terminal = remoteFlightService.queryStartTerminal(terminalId);
            orUse.setStartTerminal(terminal);
            String orderViphall = "orderViphall";
            orUse.setType(orderViphall);
            list.add(orUse);
        }
        List<Vipchannel> vipchannelList = orderVipchannelService.selectOrderVipchannelByStatus(customerId);
        for (Vipchannel vipchannel : vipchannelList) {
            OrderConductOrUse orUse = new OrderConductOrUse();
            for (OrderVipchannel orderVipchannel : vipchannel.getOrderVipchannels()) {
                orUse.setId(orderVipchannel.getOrdervipchannelId());
                orUse.setStatus(orderVipchannel.getStatus());
            }
            orUse.setName(vipchannel.getVipchannelName());
            orUse.setAddress(vipchannel.getAddress());
            String businessBeginhour = vipchannel.getBusinessBeginHour().toString();
            if (businessBeginhour != null) {
                builder = new StringBuilder(businessBeginhour);
                builder.insert(builder.length() - 2, ":");
                orUse.setBusinessBeginhour(builder.toString());
            }
            String businessEndhour = vipchannel.getBusinessEndHour().toString();
            if (businessEndhour != null) {
                builder = new StringBuilder(businessEndhour);
                builder.insert(builder.length() - 2, ":");
                orUse.setBusinessEndhour(builder.toString());
            }
            Long terminalId = vipchannel.getAirportTerminalId();
            String terminal = remoteFlightService.queryStartTerminal(terminalId);
            orUse.setStartTerminal(terminal);
            String orderVipchannel = "orderVipchannel";
            orUse.setType(orderVipchannel);
            list.add(orUse);
        }
        return list;
    }

    /**
     * 订单二维码
     *
     * @param customerId
     * @param orderviphallId
     * @return
     */
    @Override
    public Map<String, Object> orderViphallQRCode(Long customerId, Long orderviphallId) throws Exception {
        List<CustomerCard> customerCards = remoteCustomerService.queryCardIdByCustomerId(customerId);
        if (customerCards != null && customerCards.size() > 0) {
//            for (CustomerCard customerCard : customerCards) {
            List<OrderViphall> orderViphallList = orderViphallMapper.orderViphallQRCode(customerId, orderviphallId);
//                if (orderViphallList != null && orderViphallList.size() > 0){
//                    break;
//                }
//            }
//
//            if (orderViphallList == null || orderViphallList.size() <= 0){
//                throw new Exception("未查到数据");
//            }

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Map<String, Object> map = new HashMap<>();
            for (OrderViphall orderViphall : orderViphallList) {
                String format = dateFormat.format(orderViphall.getArrivalviphallTime());
                map.put("deptairportName", orderViphall.getDeptairportName());
                map.put("arrivalviphallTime", format);
                map.put("peopleNumber", orderViphall.getPeopleNumber());
                for (Viphall viphall : orderViphall.getViphalls()) {
                    map.put("viphallName", viphall.getViphallName());
                    map.put("address", viphall.getAddress());
                    map.put("securityCheckLocation", viphall.getSecurityCheckLocation());
                    String terminal = remoteFlightService.queryStartTerminal(viphall.getAirportTerminalId());
                    map.put("startTerminal", terminal);
                }
                try {
                    String base64 = encodeData(String.valueOf(map));
                    map.put("base64", base64);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return map;
        } else {
            throw new Exception("未查到会员卡信息");
        }
    }

    /**
     * 二维码解密
     */
    @Override
    public Map<String, Object> QRCodeDecryption(String decryption) {
        String[] split = new String[0];
        try {
            split = decodeData(decryption).replace("{", "").replace("}", "").split(", ");

        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String, Object> map = new HashMap<>();
        for (String str : split) {
            map.put(str.split("=")[0], str.split("=")[1]);
        }
        return map;
    }

    /**
     * 贵宾厅订单详情
     */
    @Override
    public List<OrderViphall> selectOrderViphallByCustomerId(Long customerId, Long orderviphallId) {
        return orderViphallMapper.selectOrderViphallByCustomerId(customerId, orderviphallId);
    }


    @Override
    public int updateOrderViphallByIsDeleted(Long orderviphallId) {
        return orderViphallMapper.updateOrderViphallByIsDeleted(orderviphallId);
    }

    /**
     * 取消订单-立即支付（修改状态）-申请退款
     */
    @Override
    public int updateOrderViphallByPaymentStatus(Long customerId, Long orderviphallId, String type) {
        int count = 0;
        OrderViphall orderViphall = orderViphallMapper.selectOrderViphallBycustomerIdAndOrderViphallId(customerId, orderviphallId);
        if (type.equals("cancel")) {//取消
            if (orderViphall.getPaymentStatus().equals("unpaid")) {//判断支付状态是否为未支付
                count = orderViphallMapper.updateOrderViphallByPaymentStatus(orderviphallId, type);
            } else {
                throw new LoginException("该订单已支付，无法取消！");
            }
        } else if (type.equals("topay")) {//支付
            if (orderViphall.getPaymentStatus().equals("unpaid") && orderViphall.getStatus().equals("unpaid")) {
                count = orderViphallMapper.updateOrderViphallByPaymentStatusAndOrderviphallId(orderviphallId);
            } else {
                throw new LoginException("该订单无法支付！");
            }
        } else if (type.equals("refund")) {//退款
            if (orderViphall.getPaymentStatus().equals("paid")) {
                count = orderViphallMapper.updateOrderViphallBy(orderviphallId);
            } else {
                throw new LoginException("该订单无法支付！");
            }
        }
        return count;
    }

    /**
     * 修改订单
     */
    @Override
    public int updateOrderViphallByContactPhone(OrderViphall orderviphall) {
        return orderViphallMapper.updateOrderViphallByContactPhone(orderviphall);
    }

    @Override
    public Map<String, Object> queryViphallTrip(Long orderviphallId) {
        List<OrderViphall> orderViphallList = orderViphallMapper.queryViphallTrip(orderviphallId);
        Map<String, Object> map = new HashMap<>();
        StringBuilder builder;
        for (OrderViphall orderViphall : orderViphallList) {
            map.put("peopleNumber", orderViphall.getPeopleNumber());
            for (Viphall viphall : orderViphall.getViphalls()) {
                map.put("viphallId", viphall.getViphallId());
                map.put("viphallName", viphall.getViphallName());
                map.put("address", viphall.getAddress());
                String businessBeginhour = viphall.getBusinessBeginhour();
                if (businessBeginhour != null) {
                    builder = new StringBuilder(businessBeginhour);
                    map.put("businessBeginhour", builder.insert(builder.length() - 2, ":"));
                }
                String businessEndhour = viphall.getBusinessEndhour();
                if (businessEndhour != null) {
                    builder = new StringBuilder(businessEndhour);
                    map.put("businessEndhour", builder.insert(builder.length() - 2, ":"));
                }
                List viphallAttachmentList = new ArrayList();
                for (ViphallAttachment viphallAttachment : viphall.getViphallAttachmentList()) {
                    String attachPath = viphallAttachment.getAttachPath();
                    viphallAttachmentList.add(attachPath);
                }
                map.put("attachPath", viphallAttachmentList);
                String airportId = viphall.getAirportCode();
                String airPortName = remoteFlightService.queryAirPortName(airportId);
                map.put("airPortName", airPortName);
            }
        }
        return map;
    }

    @Override
    public OrderViphall queryItinerary(Long customerId) {
        OrderViphall viphall = orderViphallMapper.queryItinerary(customerId, CustomerConstants.waitPay.getValue());
        return viphall;
    }

    @Override
    public Map<String, Object> selectItinerary(Long orderviphallId) {
        OrderViphall orderViphall = orderViphallMapper.selectItinerary(orderviphallId);
        Map<String, Object> map = new HashMap<>();
        StringBuilder builder;
        map.put("peopleNumber", orderViphall.getPeopleNumber());
        for (Viphall viphall : orderViphall.getViphalls()) {
            map.put("viphallId", viphall.getViphallId());
            map.put("viphallName", viphall.getViphallName());
            map.put("address", viphall.getAddress());
            String businessBeginhour = viphall.getBusinessBeginhour();
            if (businessBeginhour != null) {
                builder = new StringBuilder(businessBeginhour);
                map.put("businessBeginhour", builder.insert(builder.length() - 2, ":"));
            }
            String businessEndhour = viphall.getBusinessEndhour();
            if (businessEndhour != null) {
                builder = new StringBuilder(businessEndhour);
                map.put("businessEndhour", builder.insert(builder.length() - 2, ":"));
            }
            map.put("freeMember", viphall.getFreeMember());
            List viphallAttachmentList = new ArrayList();
            for (ViphallAttachment viphallAttachment : viphall.getViphallAttachmentList()) {
                String attachPath = viphallAttachment.getAttachPath();
                viphallAttachmentList.add(attachPath);
            }
            map.put("attachPath", viphallAttachmentList);
            for (ContractLinkViphallPrice contractLinkViphallPrice : viphall.getContractLinkViphallPriceList()) {
                map.put("retailPrice", contractLinkViphallPrice.getRecommendedRetailPrice());
                map.put("salePrice", contractLinkViphallPrice.getSalePrice());
            }
            String airportId = viphall.getAirportCode();
            String airPortName = remoteFlightService.queryAirPortName(airportId);
            map.put("airPortName", airPortName);
        }
        return map;
    }

    //微信小程序支付
    @Override
    public Map<String, Object> wechatPay(String openId, Long orderNumber, BigDecimal amount, String type) throws Exception {
        OrderViphall viphall = orderViphallMapper.queryByOrderNumber(orderNumber);
        if (amount != null && amount.compareTo(new BigDecimal(0)) > 0){
            viphall.setDepositAmount(amount);
            viphall.setPaymentAmount(viphall.getPaymentAmount().subtract(amount));
            int i = orderViphallMapper.updateOrderViphall(viphall);
            if (i <= 0){
                throw new Exception("修改订单预留款失败");
            }

            DepositBusinessApi depositBusiness = new DepositBusinessApi();
            depositBusiness.setRemark("贵宾厅微信小程序支付");
            depositBusiness.setState("false");
            depositBusiness.setBusinessType(EmHelper.businessType.SERVICE.getValue());
            depositBusiness.setOperatorId(1L);
            depositBusiness.setOrdersourceid(type);
            depositBusiness.setCustomerId(viphall.getCustomerId());
            depositBusiness.setDetailamount(amount);
            depositBusiness.setChangetype(2l);
            depositBusiness.setLockState("false");
            depositBusiness.setOrderId(Long.valueOf(viphall.getOrderNumber()));
            depositBusiness.setDrawState("false");
            Long aLong = remoteCustomerService.addReserveMoney(depositBusiness);
            if (aLong <= 0){
                throw new Exception("添加预留款记录失败");
            }

            Map<String, Object> map = new HashMap<>();
            map.put("id", aLong);
            map.put("remark", "贵宾厅微信小程序支付");
            boolean b = remoteCustomerService.manageAudit(map);
            if (!b){
                throw new Exception("审核失败，请进行人工审核");
            }
        }

        String notifyUrl = "/service/callback/vipHallWechatPayCallback";
        R<Map> wechatJSAPIPayParam = payService.getWechatJSAPIPayParam(openId, viphall.getPaymentAmount(), String.valueOf(orderNumber), notifyUrl);
        if (wechatJSAPIPayParam.getCode() == 200) {
            viphall.setPayType(BusinessTypeConstants.Wechat.getValue());
            orderViphallMapper.updateOrderViphall(viphall);
            return wechatJSAPIPayParam.getData();
        }
        return null;
    }

    @Override
    public int updateByOrderNumber(OrderViphall orderViphall) {
        return orderViphallMapper.updateByOrderNumber(orderViphall);
    }

    /**
     * 查询会员贵宾厅订单列表
     */
    @Override
    public List<OrderViphall> selectOrderViphallByCustomer(Long customerId, String type) throws Exception {
//        List<CustomerCard> customerCards = remoteCustomerService.queryCardIdByCustomerId(customerId);//会员 卡号
//
//        for (CustomerCard customerCard : customerCards) {
//            if (customerCard.getCardId() != null && customerCard.getCardId() != 0){
//                Map<String, Object> map = new HashMap<>();
//                map.put("cardId", customerCard.getCardId());
//                Card card = remoteCustomerService.cardInfo(map);
//                if (card != null){
//                    customerCard.setCardLevel(card.getCardLevel());
//                }
//                else {
//                    throw new Exception("无效的会员卡");
//                }
//            }
//            else {
//                throw new Exception("会员卡没有关联卡id");
//            }
//        }
//
//        customerCards.sort((y, x) -> Double.compare(y.getCardLevel(), x.getCardLevel()));
//        CustomerCard customerCardR = customerCards.get(0);
//
//        String cardNumber = customerCardR.getCardCode();

        List<OrderViphall> orderViphallList = orderViphallMapper.VipRoomOrder(customerId, type);

        for (OrderViphall orderViphall : orderViphallList) {
            Viphall viphall = viphallMapper.viphall(orderViphall.getViphallId());
            orderViphall.setViphall(viphall);
        }

        return orderViphallList;
    }

    @Override
    public int queryVipHallOrderNumber(Long customerId) {
        return orderViphallMapper.queryVipHallOrderNumber(customerId);
    }

    /**
     * 贵宾厅订单列表
     */
    @Override
    public List<OrderViphall> selectVipchannelOrederListVo(VipchannelOrederParameterVo vipchannelOrederParameterVo) {
        List<OrderViphall> orderViphallList = orderViphallMapper.selectOrderViphalls(vipchannelOrederParameterVo);


        if (orderViphallList != null && orderViphallList.size() > 0) {
            for (OrderViphall orderViphall : orderViphallList) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", orderViphall.getDepartmentId());
                Department department = remoteCustomerService.deptName(map);
                if (department != null) {
                    orderViphall.setDeptName(department.getDeptName());
                }

                Map<String, Object> name = new HashMap<>();
                name.put("airportId", orderViphall.getDepartureairportCode());
                AirportApi airportApi = remoteFlightService.getAirportInfoByAirportName(name);
                if (airportApi != null) {
                    orderViphall.setDepartureairportCode(airportApi.getAirportName());
                }
            }
        }
        return orderViphallList;
    }

    /**
     * 贵宾厅订单详细
     */
    @Override
    public OrderViphallDetailsVo selectVipHallDetails(Long orderId, String orderNum) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        if ((orderId != null && orderId != 0) || (orderNum != null && !orderNum.equals(""))) {
            OrderViphall orderViphall;
            if (orderId != null) {
                orderViphall = orderViphallMapper.selectVipHallDetails(orderId);
            } else {
                orderViphall = orderViphallMapper.vipHallDetails(orderNum);
            }

            List<OrderOperationlog> orderOperationlogs = null;
            if (orderNum != null && !orderNum.equals("")){
                orderOperationlogs = orderOperationlogMapper.orderOperationlogList(Long.valueOf(orderNum));
            }

            Customer customer = null;
            if (orderViphall.getCustomerId() != null && orderViphall.getCustomerId() != 0) {
                customer = remoteCustomerService.getCustomerId(orderViphall.getCustomerId()).getData();
            }

            if (orderViphall != null) {
                OrderViphallDetailsVo orderViphallDetailsVo = new OrderViphallDetailsVo();
                orderViphallDetailsVo.setOrderId(orderViphall.getOrderviphallId());
                if (customer != null) {
                    orderViphallDetailsVo.setCustomerName(customer.getCustomerName());
                    orderViphallDetailsVo.setCustomerPhone(customer.getContractPhoneOne());
                }
                orderViphallDetailsVo.setCustomerCard(orderViphall.getCardNumber());
                if (orderViphall.getCreateTime() != null) {
                    orderViphallDetailsVo.setCreateTime(format.format(orderViphall.getCreateTime()));
                }
                orderViphallDetailsVo.setSourceCompanyId(orderViphall.getSourcecompanyId());
                orderViphallDetailsVo.setSourceAppId(orderViphall.getSourceappId());
                orderViphallDetailsVo.setContactName(orderViphall.getContactName());
                orderViphallDetailsVo.setContactPhone(orderViphall.getContactPhone());
                orderViphallDetailsVo.setOrderNum(orderViphall.getOrderNumber().toString());
                orderViphallDetailsVo.setArrivalVipHallTime(orderViphall.getArrivalAirportcode());
                orderViphallDetailsVo.setReserveNum(orderViphall.getReserveNum());
                orderViphallDetailsVo.setAdoptPeopleNumber(orderViphall.getAdoptPeopleNumber());
                orderViphallDetailsVo.setCityName(orderViphall.getDepartureCity());
                orderViphallDetailsVo.setSetOffAirport(orderViphall.getSetOffAirport());
                orderViphallDetailsVo.setDepartuprairportTerminalName(orderViphall.getArrivalAirportterminalname());
                orderViphallDetailsVo.setFlightNumber(orderViphall.getFlightNumber());
                orderViphallDetailsVo.setDeparturesCity(orderViphall.getDepartureCity());
                orderViphallDetailsVo.setArrivalCity(orderViphall.getArrivalCity());
                if (orderViphall.getDepartureTime() != null) {
                    orderViphallDetailsVo.setDepartureTime(format.format(orderViphall.getDepartureTime()));
                }
                if (orderViphall.getArrivalTime() != null) {
                    orderViphallDetailsVo.setArrivalTime(format.format(orderViphall.getArrivalTime()));
                }
                if (orderViphall.getTotalrecommendedRetailprice() != null && orderViphall.getTotalrecommendedRetailprice().compareTo(new BigDecimal(0)) != 0) {
                    orderViphallDetailsVo.setTotalReCommenedRetatlPrice(orderViphall.getTotalrecommendedRetailprice().toString());
                }
                if (orderViphall.getTotalsalePrice() != null && orderViphall.getTotalsalePrice().compareTo(new BigDecimal(0)) != 0) {
                    orderViphallDetailsVo.setTotalsalePrice(orderViphall.getTotalsalePrice().toString());
                }
                orderViphallDetailsVo.setPaymentStatus(orderViphall.getPaymentStatus());
                if (orderViphall.getPaymentAmount() != null && orderViphall.getPaymentAmount().compareTo(new BigDecimal(0)) != 0) {
                    orderViphallDetailsVo.setPaymentAmount(orderViphall.getPaymentAmount().toString());
                }
                if (orderViphall.getVoucherAmount() != null && orderViphall.getVoucherAmount().compareTo(new BigDecimal(0)) != 0) {
                    orderViphallDetailsVo.setVoucherAmount(orderViphall.getVoucherAmount().toString());
                }
                if (orderViphall.getPoints() != null && orderViphall.getPoints().compareTo(new BigDecimal(0)) != 0) {
                    orderViphallDetailsVo.setPoints(orderViphall.getPoints().toString());
                }
                if (orderViphall.getDepositAmount() != null && orderViphall.getDepositAmount().compareTo(new BigDecimal(0)) != 0) {
                    orderViphallDetailsVo.setDepositAmount(orderViphall.getDepositAmount().toString());
                }
                if (orderViphall.getCouponAmount() != null && orderViphall.getCouponAmount().compareTo(new BigDecimal(0)) != 0) {
                    orderViphallDetailsVo.setCouponAmount(orderViphall.getCouponAmount().toString());
                }
                if (orderViphall.getFreeNum() != null && orderViphall.getFreeNum() != 0) {
                    orderViphallDetailsVo.setFreeNum(orderViphall.getFreeNum().toString());
                }
                List<OrderOperationlogVo> operationRecord = new ArrayList<>();
                if (orderOperationlogs != null && orderOperationlogs.size() > 0) {
                    for (OrderOperationlog orderOperationlog : orderOperationlogs) {
                        OrderOperationlogVo orderOperationlogVo = new OrderOperationlogVo();
                        orderOperationlogVo.setOperationId(orderOperationlog.getOperationId());
                        orderOperationlogVo.setOperationName(orderOperationlog.getOperationName());
                        orderOperationlogVo.setOperatorName(orderOperationlog.getOperatorName());
                        if (orderOperationlog.getCreateTime() != null) {
                            orderOperationlogVo.setCreateTime(format.format(orderOperationlog.getCreateTime()));
                        }
                        orderOperationlogVo.setMemo(orderOperationlog.getMemo());
                        operationRecord.add(orderOperationlogVo);
                    }
                }
                orderViphallDetailsVo.setOperationRecord(operationRecord);
                return orderViphallDetailsVo;
            } else {
                throw new Exception("未查到信息");
            }
        } else {
            throw new Exception("缺少必要参数");
        }
    }

    /**
     * 贵宾厅订单详细+orderNumber
     */
    @Override
    public OrderViphallDetailsVo selectVipHallDetailsByorderNumber(Long orderNumber) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        if (orderNumber != null && orderNumber != 0) {
            OrderViphall orderViphall = orderViphallMapper.selectVipHallDetailsByorderNumber(orderNumber);
            List<OrderOperationlog> orderOperationlogs = orderOperationlogMapper.orderOperationlogList(orderNumber);
            Customer customer = null;
            if (orderViphall.getCustomerId() != null && orderViphall.getCustomerId() != 0) {
                customer = remoteCustomerService.getCustomerId(orderViphall.getCustomerId()).getData();
            }

            if (orderViphall != null) {
                OrderViphallDetailsVo orderViphallDetailsVo = new OrderViphallDetailsVo();
                orderViphallDetailsVo.setOrderId(orderViphall.getOrderviphallId());
                if (customer != null) {
                    orderViphallDetailsVo.setCustomerName(customer.getCustomerName());
                    orderViphallDetailsVo.setCustomerPhone(customer.getContractPhoneOne());
                }
                orderViphallDetailsVo.setCustomerCard(orderViphall.getCardNumber());
                if (orderViphall.getCreateTime() != null) {
                    orderViphallDetailsVo.setCreateTime(format.format(orderViphall.getCreateTime()));
                }
                orderViphallDetailsVo.setSourceCompanyId(orderViphall.getSourcecompanyId());
                orderViphallDetailsVo.setSourceAppId(orderViphall.getSourceappId());
                orderViphallDetailsVo.setContactName(orderViphall.getContactName());
                orderViphallDetailsVo.setContactPhone(orderViphall.getContactPhone());
                orderViphallDetailsVo.setOrderNum(orderViphall.getOrderNumber().toString());
                orderViphallDetailsVo.setArrivalVipHallTime(orderViphall.getArrivalAirportcode());
                orderViphallDetailsVo.setReserveNum(orderViphall.getReserveNum());
                orderViphallDetailsVo.setAdoptPeopleNumber(orderViphall.getAdoptPeopleNumber());
                orderViphallDetailsVo.setCityName(orderViphall.getDepartureCity());
                orderViphallDetailsVo.setSetOffAirport(orderViphall.getSetOffAirport());
                orderViphallDetailsVo.setDepartuprairportTerminalName(orderViphall.getArrivalAirportterminalname());
                orderViphallDetailsVo.setFlightNumber(orderViphall.getFlightNumber());
                orderViphallDetailsVo.setDeparturesCity(orderViphall.getDepartureCity());
                orderViphallDetailsVo.setArrivalCity(orderViphall.getArrivalCity());
                if (orderViphall.getDepartureTime() != null) {
                    orderViphallDetailsVo.setDepartureTime(format.format(orderViphall.getDepartureTime()));
                }
                if (orderViphall.getArrivalTime() != null) {
                    orderViphallDetailsVo.setArrivalTime(format.format(orderViphall.getArrivalTime()));
                }
                if (orderViphall.getTotalrecommendedRetailprice() != null && orderViphall.getTotalrecommendedRetailprice().compareTo(new BigDecimal(0)) != 0) {
                    orderViphallDetailsVo.setTotalReCommenedRetatlPrice(orderViphall.getTotalrecommendedRetailprice().toString());
                }
                if (orderViphall.getTotalsalePrice() != null && orderViphall.getTotalsalePrice().compareTo(new BigDecimal(0)) != 0) {
                    orderViphallDetailsVo.setTotalsalePrice(orderViphall.getTotalsalePrice().toString());
                }
                orderViphallDetailsVo.setPaymentStatus(orderViphall.getPaymentStatus());
                if (orderViphall.getPaymentAmount() != null && orderViphall.getPaymentAmount().compareTo(new BigDecimal(0)) != 0) {
                    orderViphallDetailsVo.setPaymentAmount(orderViphall.getPaymentAmount().toString());
                }
                if (orderViphall.getVoucherAmount() != null && orderViphall.getVoucherAmount().compareTo(new BigDecimal(0)) != 0) {
                    orderViphallDetailsVo.setVoucherAmount(orderViphall.getVoucherAmount().toString());
                }
                if (orderViphall.getPoints() != null && orderViphall.getPoints().compareTo(new BigDecimal(0)) != 0) {
                    orderViphallDetailsVo.setPoints(orderViphall.getPoints().toString());
                }
                if (orderViphall.getDepositAmount() != null && orderViphall.getDepositAmount().compareTo(new BigDecimal(0)) != 0) {
                    orderViphallDetailsVo.setDepositAmount(orderViphall.getDepositAmount().toString());
                }
                if (orderViphall.getCouponAmount() != null && orderViphall.getCouponAmount().compareTo(new BigDecimal(0)) != 0) {
                    orderViphallDetailsVo.setCouponAmount(orderViphall.getCouponAmount().toString());
                }
                if (orderViphall.getFreeNum() != null && orderViphall.getFreeNum() != 0) {
                    orderViphallDetailsVo.setFreeNum(orderViphall.getFreeNum().toString());
                }
                List<OrderOperationlogVo> operationRecord = new ArrayList<>();
                if (orderOperationlogs != null && orderOperationlogs.size() > 0) {
                    for (OrderOperationlog orderOperationlog : orderOperationlogs) {
                        OrderOperationlogVo orderOperationlogVo = new OrderOperationlogVo();
                        orderOperationlogVo.setOperationId(orderOperationlog.getOperationId());
                        orderOperationlogVo.setOperationName(orderOperationlog.getOperationName());
                        orderOperationlogVo.setOperatorName(orderOperationlog.getOperatorName());
                        if (orderOperationlog.getCreateTime() != null) {
                            orderOperationlogVo.setCreateTime(format.format(orderOperationlog.getCreateTime()));
                        }
                        orderOperationlogVo.setMemo(orderOperationlog.getMemo());
                        operationRecord.add(orderOperationlogVo);
                    }
                }
                orderViphallDetailsVo.setOperationRecord(operationRecord);
                return orderViphallDetailsVo;
            } else {
                throw new Exception("未查到信息");
            }
        } else {
            throw new Exception("缺少必要参数");
        }
    }

    ;

    /**
     * 行程贵宾厅订单
     */
    @Override
    public JourneyOrderViphallVo journeyOrderViphallVo(Long orderviphallId) {
        OrderViphall orderViphall = orderViphallMapper.selectVipHallDetails(orderviphallId);
        JourneyOrderViphallVo journeyOrderViphallVo = new JourneyOrderViphallVo();
        journeyOrderViphallVo.setOrderId(orderViphall.getOrderviphallId().toString());
        journeyOrderViphallVo.setBusinessType(EmHelper.businessType.SERVICE.getValue());
        journeyOrderViphallVo.setActualPriceTotal(orderViphall.getPaymentAmount().toString());
        if (orderViphall.getPaymentStatus().equals(TrainOrderEnum.paid.getValue())) {
            journeyOrderViphallVo.setOrderStatusID("未支付");
        } else if (orderViphall.getPaymentStatus().equals(TrainOrderEnum.unpaid.getValue())) {
            journeyOrderViphallVo.setOrderStatusID(orderViphall.getStatus());
        } else if (orderViphall.getPaymentStatus().equals(TrainOrderEnum.cancellation.getValue())) {
            journeyOrderViphallVo.setOrderStatusID("已退款");
        } else if (orderViphall.getPaymentStatus().equals(CustomerConstants.cancelPay.getValue())) {
            journeyOrderViphallVo.setOrderStatusID("取消支付");//cancelPay
        }
        journeyOrderViphallVo.setContactPhone(orderViphall.getContactPhone());
        journeyOrderViphallVo.setPeopleNumber(orderViphall.getPeopleNumber().toString());
        Viphall viphall = viphallMapper.viphall(orderViphall.getViphallId());
        journeyOrderViphallVo.setViphallName(viphall.getViphallName());
        journeyOrderViphallVo.setAddress(viphall.getAddress());
        journeyOrderViphallVo.setBusinessBeginhour(viphall.getBusinessBeginhour());
        journeyOrderViphallVo.setBusinessEndhour(viphall.getBusinessEndhour());
        return journeyOrderViphallVo;
    }

    /**
     * 贵宾厅退单
     */
    @Override
    public int chargebackOrderViphall(Long orderviphallId) {
        int i = orderViphallMapper.chargebackOrderViphall(orderviphallId);
        return i;
    }

    /**
     * 订单号获取贵宾厅订单信息
     */
    @Override
    public OrderViphall orderNum(String orderNum) {
        OrderViphall orderViphall = orderViphallMapper.vipHallDetails(orderNum);
        return orderViphall;
    }

    /**
     * 员工所属部门贵宾厅列表
     */
    @Override
    public List<OrderViphall> deptVipHallOrderList(Long id) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        Employee employee = remoteCustomerService.employeeNameList(map);
        if (employee != null) {
            List<OrderViphall> orderViphallList = orderViphallMapper.deptVipHallOrderList(employee.getDeptId());
            if (orderViphallList != null && orderViphallList.size() > 0) {
                for (OrderViphall orderViphall : orderViphallList) {
                    if (orderViphall.getDepartmentId() != null) {
                        Map<String, Object> deptMap = new HashMap<>();
                        deptMap.put("id", orderViphall.getDepartmentId());
                        Department department = remoteCustomerService.deptName(deptMap);
                        if (department != null) {
                            orderViphall.setDeptName(department.getDeptName());
                        }
                    }
                    if (orderViphall.getCustomerId() != null) {
                        CustomerIdVoApi customerIdVoApi = new CustomerIdVoApi();
                        customerIdVoApi.setCustomerId(orderViphall.getCustomerId());
                        customerIdVoApi = remoteCustomerService.customerIdApi(customerIdVoApi);
                        if (customerIdVoApi != null) {
                            orderViphall.setCustomerName(customerIdVoApi.getCustomerName());
                        }
                    }
                }
                return orderViphallList;
            }
        }
        return null;
    }

    @Override
    public String getVipHallOrderQRCode(OrderQRCodeVo orderQRCodeVo) {
        String qrCodeInfo = JSON.toJSONString(orderQRCodeVo);
        return AesUtil.encrypt(qrCodeInfo, JingTu.getInstance().getQRCodeKey());
    }

    @Override
    public AjaxResult checkViphallOrderORCode(String qrCode, String userCount, String deptId) {
        try {
            String jsonInfo = AesUtil.decrypt(qrCode, JingTu.getInstance().getQRCodeKey());
            OrderQRCodeVo orderQRCodeVo = JSON.parseObject(jsonInfo, OrderQRCodeVo.class);
            Viphall viphall = new Viphall();
            viphall.setDeptId(Long.valueOf(deptId));
            List<Viphall> lstVipHall = viphallService.selectViphallLists(viphall);
            if (CollectionUtil.isEmpty(lstVipHall)) {
                return AjaxResult.error("该员工不属于贵宾厅员工无法核销！");
            }
            boolean found = remoteCustomerService.infiniteVIPHall(orderQRCodeVo.getCustomerId());
            if (found) {
                KtserviceOrderChannelViphall orderChannel = new KtserviceOrderChannelViphall();
                orderChannel.setTickertNo("");
                orderChannel.setCardNumber(orderQRCodeVo.getCustomerId().toString());
                orderChannel.setUseCount(Long.valueOf(userCount));
                orderChannel.setUseTime(DateUtils.getNowDate());
                orderChannel.setProductUniquecode(qrCode);
                if (lstVipHall.size() > 0) {
                    orderChannel.setViphallId(lstVipHall.get(0).getViphallId());
                }
                orderChannel.setChannel(orderQRCodeVo.sourceWay.getValue());
                channelService.insertKtserviceOrderChannel(orderChannel);
                return AjaxResult.success("贵宾厅核销成功！");
            } else {
                OrderViphall viphallOrder = orderViphallService.selectOrderViphallById(orderQRCodeVo.getOrderId());
                List<KtserviceOrderChannelViphall> lstServiceOrders = channelService.selectServiceOrderByOrderId(orderQRCodeVo.getOrderId());
                if (lstServiceOrders.size() > 0) {
                    long usedCount = lstServiceOrders.stream().mapToLong(KtserviceOrderChannelViphall::getUseCount).sum();
                    if ((usedCount + Long.valueOf(userCount)) >= viphallOrder.getPeopleNumber()) {
                       return AjaxResult.error("该订单已经超出使用数量！");
                    }
                }
                if (Long.valueOf(userCount)>viphallOrder.getPeopleNumber()) {
                    return AjaxResult.error("核销数量大于订单使用数量！");
                }
                KtserviceOrderChannelViphall orderChannel = new KtserviceOrderChannelViphall();
                orderChannel.setTickertNo("");
                orderChannel.setOrderId(orderQRCodeVo.getOrderId());
                orderChannel.setUseCount(Long.valueOf(userCount));
                orderChannel.setUseTime(DateUtils.getNowDate());
                orderChannel.setProductUniquecode(qrCode);
                if (lstVipHall.size() > 0) {
                    orderChannel.setViphallId(lstVipHall.get(0).getViphallId());
                }
                orderChannel.setChannel(orderQRCodeVo.sourceWay.getValue());
                channelService.insertKtserviceOrderChannel(orderChannel);
                return AjaxResult.success("贵宾厅核销成功！");
            }
        } catch (Exception e) {
            return AjaxResult.error("贵宾厅核销失败！");
        }
    }

    /**
     * BASE64加密
     */
    private static final String UTF_8 = "UTF-8";

    public static String encodeData(String inputData) throws Exception{
        return new String(Base64.encodeBase64(inputData.getBytes(UTF_8)), UTF_8);
    }

    /**
     * BASE64解密
     * @param inputData
     * @return
     * @throws Exception
     */
    public static String decodeData(String inputData) throws Exception {
        return new String(Base64.decodeBase64(inputData.getBytes(UTF_8)), UTF_8);
    }

}
